import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm';
import { ChargeStrategy } from 'src/entities/ChargeStrategy';

@Injectable()
export class ChargeStrategyService {
    constructor(
        @InjectRepository(ChargeStrategy) protected repository:Repository<ChargeStrategy>
    ){}

    async strategy(strategyId:number, fields?:(keyof ChargeStrategy)[]) {
        let strategy = await this.repository.findOne(strategyId, {
            select : fields
        })

        if(strategy && strategy.rules) {
            const rules:any[] = []
            const len = (strategy.rules as any[]).length
            for(let i = 0; i < len;) {
                let tmp = strategy.rules[i]
                let _i = i + 1
                if(_i >= len) {
                    rules.push(tmp)
                    break
                }
                for(; _i < len; _i ++) {
                    if(tmp.w != strategy.rules[_i].w) {
                        rules.push(tmp)
                        break
                    }
                }
    
                i = _i
            }

            strategy.rules = rules.map((rule, index) => ({min : index == 0 ? 0 : rules[index - 1].w, max : rule.w, amount : rule.a}))
        }
        
        return strategy
    }
}
